import { createDarkModeStyle, DarkModeSettings } from '@/entrypoints/core/darkMode';

export default defineContentScript({
  matches: ['<all_urls>'],
  main() {
    console.log('Dark Reader Clone content script loaded for:', window.location.href);

    let darkModeStyle: HTMLStyleElement | null = null;

    function applyDarkMode(settings: DarkModeSettings) {
      console.log('Applying dark mode settings:', settings);
      if (!darkModeStyle) {
        darkModeStyle = document.createElement('style');
        darkModeStyle.id = 'dark-reader-clone-style';
        document.head.appendChild(darkModeStyle);
      }
      darkModeStyle.textContent = createDarkModeStyle(settings);
    }

    // 创建一个长连接
    const port = browser.runtime.connect({ name: 'dark-mode-port' });

    // 监听来自背景脚本的消息
    port.onMessage.addListener((message) => {
      console.log('Content script received message:', message);
      if (message.type === 'updateDarkMode') {
        console.log('Updating dark mode settings:', message.settings);
        applyDarkMode(message.settings);
      }
    });

    // 从存储中获取设置
    browser.storage.sync.get('darkModeSettings').then((result) => {
      const settings: DarkModeSettings = result.darkModeSettings || {
        brightness: 100,
        contrast: 100,
        sepia: 0,
        enabled: true
      };

      applyDarkMode(settings);
    });

    // 使用 MutationObserver 确保我们的样式始终存在
    const observer = new MutationObserver(() => {
      if (darkModeStyle && !document.head.contains(darkModeStyle)) {
        console.log('Re-inserting dark mode style');
        document.head.appendChild(darkModeStyle);
      }
    });

    observer.observe(document.head, { childList: true, subtree: true });
  },
});